<?php
declare(strict_types=1);

namespace App\Task;

use App\Exception\BusinessException;
use App\Model\ContentItem;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Redis\Redis;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;

/**
 * @Crontab(
 *     name="SetValidIdRangeTask",
 *     rule="*\/3 * * * *",
 *     callback="execute",
 *     singleton=true,
 *     onOneServer=true,
 *     mutexPool="default",
 *     mutexExpires=60,
 *     memo="设置文章有效的ID范围"
 * )
 */
class SetValidIdRangeTask
{
    public function execute(): void
    {
        $model = ContentItem::query()
            ->selectRaw('MAX(`id`) AS `max_id`')
            ->selectRaw('MIN(`id`) AS `min_id`')
            ->where('status', '=', 4)
            ->where('main_id', '=', 0)
            ->where('type_id', '=', 0)
            ->whereNull('deleted_at')
            ->first();
        if (!$model) {
            throw new BusinessException(0, '数据查询失败!');
        }
        /* @var Redis $redis */
        $redis = ApplicationContext::getContainer()->get(RedisFactory::class)->get('business');
        if (!$redis) {
            throw new BusinessException(0, '获取Redis失败!');
        }
        $setResult = $redis->hMSet('item_id_range', [
            'min' => $model->min_id,
            'max' => $model->max_id,
        ]);
        if (!$setResult) {
            throw new BusinessException(0, 'Redis写入失败!');
        }
    }
}
